package com.hk.kindheartedness;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.hk.kindheartedness.db.DBOpenHelper;
import com.hk.kindheartedness.util.DateUtil;
import com.hk.kindheartedness.util.ToastUtil;

import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 患者预约缴费新增业务
 */
public class PatientSaveSubscribeActivity extends AppCompatActivity {

    //    Initialize Toast
    private Toast toast;

    //    Initialize intent
    private Intent intent;

    //    声明DBOpenHelper对象
    private DBOpenHelper dbOpenHelper;

    //    Initialize ListView
    private ListView queryRegistrationTimeListView;

    private String doctorId,registrationDate,loginUserId;

    private TextView doctorName,doctorAge,doctorSex;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_patient_save_subscribe);
//        实例化
        dbOpenHelper = new DBOpenHelper(PatientSaveSubscribeActivity.this, "db_kindheartedness", null, 1);
//        获取ListView的控制权
        queryRegistrationTimeListView = findViewById(R.id.queryRegistrationTimeListView);
//        获取文本控制权
        doctorName = findViewById(R.id.doctorName);
        doctorAge = findViewById(R.id.doctorAge);
        doctorSex = findViewById(R.id.doctorSex);
//        提取出传递的参数
        final Intent intent2 = getIntent();
        final Bundle bundle = intent2.getExtras();
//        提取出科室Id和名称及登录ID
        doctorId = bundle.getString("doctorId");
        registrationDate = bundle.getString("registrationDate");
        loginUserId = bundle.getString("loginUserId");
        /**
         * 1、通过当前选择的就诊日期和医生Id获取当前医生挂号就诊时间和医生个人基本信息
         * 2、获取到文本的就诊时间，通过就诊时间和日期获取到挂号记录Id、就诊费用，余的可挂号人数
         * 3、保存患者挂号预约记录、当前挂号记录余数-1
         */
        Log.i("医生Id=",doctorId);
        Log.i("就诊日期=",registrationDate);
        Log.i("当前登录用户ID=",loginUserId);
//        查询当前医生就诊时间和剩余挂号数量及费用并进行回显
        findByDateAndDoctorId(doctorId,registrationDate,loginUserId);

        //        获取ListView点击事件并进行处理
        queryRegistrationTimeListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //                获取选项中的HashMap对象
                HashMap<String, String> map = (HashMap<String, String>) queryRegistrationTimeListView.getItemAtPosition(position);
                final String registrationId = map.get("registrationId");
//                当前选定就诊时间
                final String patientRegistrationTime = map.get("registrationTime");
//        建立一个对话框
//                添加一个弹出对话框
                AlertDialog alertDialog = new AlertDialog.Builder(PatientSaveSubscribeActivity.this).create();
//                设置提示
                alertDialog.setMessage("是否预约当前时间段就诊？");
//                设置 确认按钮操作
                alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
//                      1、查询当前登录用户是否有预约
                        Cursor queryRegistrationLog = readableDatabase.query("registration_log", null, "user_id = ?", new String[]{loginUserId}, null, null, null);
                        List<String> registrationIdList = new ArrayList<>(8);
                        while (queryRegistrationLog.moveToNext()) {
                            String string = queryRegistrationLog.getString(2);
                            registrationIdList.add(string);
                        }
                        if (registrationIdList.size() != 0) {
//                            通过挂号记录查询当前那个挂号记录，获取挂号就诊时间，查看是否超过或等于选定的就诊日期
                            for (String s : registrationIdList) {
                                Cursor queryRegistrationSetting = readableDatabase.query("registration_setting", null, "id = ?", new String[]{s}, null, null, null);
                                while (queryRegistrationSetting.moveToNext()) {
                                    String registrationDate2 = queryRegistrationSetting.getString(2);
                                    String registrationTime2 = queryRegistrationSetting.getString(3);
//                                    判断已预约就诊日期是否等于当前预约日期
                                    if ((registrationDate2.equals(registrationDate)) && (registrationTime2.equals(patientRegistrationTime))) {
                                        toast = ToastUtil.toastHint(toast, PatientSaveSubscribeActivity.this, "当前已预约,不能重复预约！");
                                        return;
                                    }
                                }
                            }
                        }
//                      2、通过挂号ID查询挂号当前剩余数量，判断是否可以预约
                        Cursor queryRegistrationSetting = readableDatabase.query("registration_setting", null, "id = ?", new String[]{registrationId}, null, null, null);
                        Integer remainingNumber = null;
                        while (queryRegistrationSetting.moveToNext()) {
                            String string = queryRegistrationSetting.getString(5);
                            remainingNumber = Integer.valueOf(string);
                        }
                        if (remainingNumber == null || remainingNumber == 0) {
                            toast = ToastUtil.toastHint(toast, PatientSaveSubscribeActivity.this, "当前预约人数已满,请改天预约！");
                            return;
                        }
//                        预约人数-1
                        ContentValues contentRegistrationValues = new ContentValues();
                        contentRegistrationValues.put("remaining_number",(remainingNumber -1));
                        int update = readableDatabase.update("registration_setting", contentRegistrationValues, "id = ?", new String[]{registrationId});
//                        新增患者预约信息
                        ContentValues contentValues = new ContentValues();
                        contentValues.put("user_id",loginUserId);
                        contentValues.put("registration_id",registrationId);
                        contentValues.put("subscribe_time",DateUtil.dateString(new Date()));
                        contentValues.put("is_see_a_doctor","0");
                        contentValues.put("create_time", DateUtil.dateString(new Date()));
                        contentValues.put("update_time", DateUtil.dateString(new Date()));
                        long insert = readableDatabase.insert("registration_log", null, contentValues);
                        if (insert >= 1 && update == 1) {
                            toast = ToastUtil.toastHint(toast, PatientSaveSubscribeActivity.this, "预约成功，请按时前往就诊哦！");
                            return;
                        }
                        toast = ToastUtil.toastHint(toast, PatientSaveSubscribeActivity.this, "预约失败,请刷新重试！");
                        return;
                    }
                });
//        设置取消按钮操作
                alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        toast = ToastUtil.toastHint(toast, PatientSaveSubscribeActivity.this, "本次操作已取消！");
                        return;
                    }
                });
//          显示对话框
                alertDialog.show();


            }
        });


    }

    /**
     * 查询当前医生就诊时间和剩余挂号数量及费用并进行回显
     * @param doctorId 医生ID
     * @param registrationDate 就诊日期
     * @param loginUserId 当前患者ID
     */
    private void findByDateAndDoctorId(String doctorId, String registrationDate, String loginUserId) {
//        打开数据库
        SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
        Cursor queryUser = readableDatabase.query("user", null, "doctor_id = ?", new String[]{doctorId}, null, null, null);
        while (queryUser.moveToNext()) {
            String patientName = queryUser.getString(1);
            String patientSex = queryUser.getString(6);
            String patientAge = queryUser.getString(7);
            doctorName.setText(patientName);
            doctorAge.setText(patientAge);
            String sex = "男";
            if (patientSex.equals("1")) {
                sex = "女";
            }
            doctorSex.setText(sex);
        }

//        获取当前医生当天就诊时间
        Cursor queryRegistrationSetting = readableDatabase.query("registration_setting", null, "doctor_id = ? and registration_date = ? ", new String[]{doctorId,registrationDate}, null, null, "registration_time asc");
        //        存储获取到的数据
        List<Map<String, Object>> resultList = new ArrayList<>(6);
        while (queryRegistrationSetting.moveToNext()) {
            //        存储临时Map对象
            Map<String, Object> map = new HashMap<>(6);
            String registrationId = queryRegistrationSetting.getString(0);
            String registrationTime = queryRegistrationSetting.getString(3);
            String remainingNumber = queryRegistrationSetting.getString(5);
            String registrationMoney = queryRegistrationSetting.getString(6);
            map.put("registrationId",registrationId);
            map.put("registrationTime",registrationTime);
            map.put("registrationMoney","$ "+registrationMoney);
            map.put("remainingNumber","余："+remainingNumber);
            resultList.add(map);
        }
        //        判断是否具有就诊时间
        if (resultList == null || resultList.size() == 0) {
            toast = ToastUtil.toastHint(toast, PatientSaveSubscribeActivity.this, "医生暂无就诊时间，请稍后查看！");
            return;
        }
        SimpleAdapter simpleAdapter = new SimpleAdapter(
                PatientSaveSubscribeActivity.this,
                resultList,
                R.layout.query_patient_registration,
                new String[]{
                        "registrationId","registrationTime",
                        "registrationMoney","remainingNumber",
                },
                new int[]{
                        R.id.registrationId,R.id.patientRegistrationTime,
                        R.id.patientRegistrationMoney,R.id.registrationCount,
                }
        );
        queryRegistrationTimeListView.setAdapter(simpleAdapter);
    }

    /**
     * 断开数据库连接
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dbOpenHelper != null) {
            dbOpenHelper.close();
        }
    }

}